const app = getApp()
const to = app.require("lib/awaitTo")
const { getUser } = app.require("utils/request/user")
const { showConfirm } = app.require("lib/modal")
Component({
	options: {
		styleIsolation: 'apply-shared'
	},
	properties: {
		unreadNum: {
			type: Number
		}
	},
	data: {
		user: wx.getStorageSync('user'),
		list: [
			{ label: "我的发布", type: "myPost", func: "showPost" },
			{ label: "我的收藏", type: "myCollection", func: "showPost" },
			{ label: "我的关注", type: "myFollow", func: "showUser" },
		]
	},
	pageLifetimes: {
		show() {
			if (this.data.user) {
				this.getUser()
			}
		}
	},
	methods: {
		async getUser() {
			const [err, res] = await to(getUser(this.data.user._id), "getUser")
			if (err) { return }
			const user = res[0].data
			user.postNum = res[1].total
			user.favorNum = res[2].list.length ? res[2].list[0].favorNum : 0
			this.setData({ user })
		},
		showUserPage() {
			const { showUserPage } = app.require("utils/router/user")
			showUserPage(this.data.user._id)
		},
		showPost({ label, type }) {
			const { showPostList } = app.require("utils/router/post")
			showPostList({ title: label, type })
		},
		showUser({ label, type }) {
			const { showUserList } = app.require("utils/router/user")
			showUserList({ title: label, type })
		},
		showUserForm() {
			wx.navigateTo({
				url: '/pages/form/user-form/user-form',
			})
		},
		chooseList(e) {
			const { func, label, type } = e.target.dataset.item
			this[func]({ label, type })
		},
		async logout() {
			const res = await showConfirm("确定要退出登录吗?")
			if (!res) { return }
			wx.clearStorageSync("user")
			this.setData({ user: {} })
			app.globalData.pubSub.publish("onLogout")
		}
	}
})
